package com.chuanke.ckfamily.service.face.impl;

import java.net.URLDecoder;
import java.sql.Timestamp;

import com.chuanke.ckfamily.service.common.CacheService;
import com.chuanke.ckfamily.service.common.RSAService;
import com.chuanke.ckfamily.service.common.WyService;
import com.chuanke.ckfamily.service.util.CkServerUtil;
import com.chuanke.ckfamily.service.util.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chuanke.ckfamily.dao.user.model.User;
import com.chuanke.ckfamily.service.base.FailCode;
import com.chuanke.ckfamily.service.exception.CFException;
import com.chuanke.ckfamily.service.face.FaceService;
import com.chuanke.ckfamily.service.social.FamilyFinanceService;
import com.chuanke.ckfamily.service.user.UserService;

import javax.servlet.http.HttpServletRequest;

@Service
@Transactional
public class FaceServiceImpl implements FaceService {

    private static final Logger logger = LoggerFactory.getLogger(FaceServiceImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private FamilyFinanceService familyFinanceService;

    @Autowired
    private RSAService rsaService;

    @Autowired
    private WyService wyService;

    @Autowired
    private CacheService cacheService;

    @Override
    public void userActivity(Long uid, Long shareSize) throws CFException {
        User user = userService.findById(uid);
        if (user == null) {
            throw new CFException(FailCode.APP, "用户不存在");
        }

        // 成功执行
        if (shareSize > 0) {
            User u = new User();
            u.setId(user.getId());
            u.setActive_time((new Timestamp(System.currentTimeMillis())));
            userService.update(u);

            cacheService.delete(CacheService.KEY_PREFIX.user_share_time_.name() + uid);
            cacheService.set(CacheService.KEY_PREFIX.user_share_time_.name() + uid, u.getActive_time().getTime());

            boolean addIncome = familyFinanceService.addIncome(uid, 1L);
            if(!addIncome){
            	throw new CFException(FailCode.APP, "增加收益失败");
            }
        }
    }

    public void userUpdate(Long uid) throws Exception {
        User u = CkServerUtil.loadUser(uid);
        if (u == null) {
            throw new CFException(FailCode.APP, "用户不存在");
        }

        User old = userService.findById(uid);
        if (old == null) {
            old = u;
            userService.save(old);
            return;
        }
        User newUser = new User();
        newUser.setId(old.getId());
        newUser.setNick_name(u.getNick_name());
        newUser.setReal_name(u.getReal_name());
        newUser.setMobile(u.getMobile());
        newUser.setSex(u.getSex());
        newUser.setPic(u.getPic());
        newUser.setUpdate_time((new Timestamp(System.currentTimeMillis())));

        userService.update(newUser);
        User user = userService.findById(uid);
        if(old.hasWyId()){
        	wyService.updateUser(user);
        }
    }

    @Override
    public void userRegist(Long uid, Long elect_id) throws Exception {
        User user = userService.findById(uid);
        if (user == null) {
            throw new CFException(FailCode.APP, "用户不存在");
        }
        user.setSuper_id(elect_id);
        userService.update(user);

        logger.info("注册的用户================》user={},id={}",user,user.getId());
        if (elect_id != 0 && elect_id != null && !uid.equals(elect_id)) {
            try {
                User superUser = userService.findById(elect_id);
                familyFinanceService.addIncome(superUser.getId(), 2L);

            } catch (Exception e) {
            	e.printStackTrace();
            }
        }
    }

    @Override
    public void checkSign(HttpServletRequest request, String sign) throws Exception {
        try {
            String pk = SignUtil.getEncryptSign();
            String decryptSign = this.rsaService.decryptByPublicKey(sign.replaceAll(" ", ""),
                    SignUtil.getPublicKey(URLDecoder.decode(pk,"UTF-8").replaceAll(" ", "")));
            String realSign = SignUtil.getSign(request);
            if (!realSign.equals(decryptSign)) {
                // 解密不匹配
                throw new CFException(FailCode.APP, "解密失败");
            }
        } catch (Exception e) {
            // 解密失败
            e.printStackTrace();
            throw new CFException(FailCode.APP, "解密失败");
        }
    }

    @Override
    public void updateAllUser(){
        java.util.List<Long> ids = userService.findAllUserId();
        for(Long id : ids){
            try {
                userUpdate(id);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
